
package com.kugou.game.sdk.ui.fragment;

import java.util.UUID;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kugou.game.sdk.adapter.RechargeMoneyGridAdapter;
import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.BasePayRequestParams;
import com.kugou.game.sdk.entity.PayConstant.ChargeIndexMode;
import com.kugou.game.sdk.entity.PayConstant.ChargeType;
import com.kugou.game.sdk.interfaces.OnAliPayListener;
import com.kugou.game.sdk.protocol.AliPayTask;
import com.kugou.game.sdk.protocol.AliPayTask.AliPayHttpResponse;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;

/**
 * 描述:支付宝充值
 *
 * @author wcj
 * @since 2015年11月11日 下午2:26:34
 */
public class RechargeByAliPayFragment extends BaseRechargeFragment implements OnItemClickListener {
    /**
     * 请求支付
     */
    private final int MSG_BACK_REQUEST_PAY = 2;

    private final int MSG_REQUEST_ALIPAY_INFO = 3;

    private final int MSG_REQUEST_ALIPAY_INFO_SUCCESS = 4;

    private final int MSG_REQUEST_ALIPAY_INFO_FAILED = 5;

    /**
     * 请求支付宝支付成功
     */
    private final int MSG_ALIPAY_SUCCESS = 6;

    /**
     * 请求支付宝支付失败
     */
    private final int MSG_ALIPAY_FAILED = 7;

    /**
     * 标题栏下边的支付金额
     */
    protected TextView mCommonTipsBarMoneyNum;

    /**
     * 充值金额栏、其他金额栏
     */
    private LinearLayout mRechargeLayout, mOtherNumLayout;

    /**
     * 兑换比例
     */
    protected TextView mTvOtherNumTip;

    private GridView mGridView;

    private RechargeMoneyGridAdapter mAdapter;

    private Context mContext;

    private EditText mEtOtherNum;

    private Button mSummitBtn;

    private int mFixedNum = -1;

    private int mRechargeValue = 10;

    /**
     * 支付订单号
     */
    private String mOrderid = "";

    public static RechargeByAliPayFragment getInstance(int num, boolean rechargeYoubi) {
        RechargeByAliPayFragment fragment = new RechargeByAliPayFragment();
        fragment.mIsRechargeYoubi = rechargeYoubi;
        fragment.mFixedNum = num;
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        // showLayoutRechargeSuccess();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initViews();
        initCoupon();
        updateView();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        int viewId = Rx.layout.kg_fragment_recharge_by_ali;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            viewId = Rx.layout.kg_fragment_recharge_by_ali_land;
        }

        return inflater.inflate(viewId, null);
    }

    private static int[] sMoneys = {
            10, 20, 30, 50, 100, 200
    };

    private void initViews() {

        mCommonTipsBarMoneyNum = (TextView) findViewById(Rx.id.kg_common_tips_bar_money_num);

        mEtOtherNum = (EditText) findViewById(Rx.id.kg_et_custom_num);
        mSummitBtn = (Button) findViewById(Rx.id.kg_btn_summit);
        mSummitBtn.setText("去支付宝支付");
        mSummitBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkIsSummit()) {
                    sendEmptyBackgroundMessage(MSG_BACK_REQUEST_PAY);
                    hideSoftInput(mContext);
                    // 发送统计--点击确认支付按钮
                    sendClickConfirmRechargeBtnStatics(ChargeType.TYPE_ALIPAY, mRechargeValue);
                }
            }
        });
        mTvOtherNumTip = (TextView) findViewById(Rx.id.kg_pay_other_num_text);
        mRechargeLayout = (LinearLayout) findViewById(Rx.id.kg_layout_recharge_content);
        mOtherNumLayout = (LinearLayout) findViewById(Rx.id.kg_layout_other_money);

        mGridView = (GridView) findViewById(Rx.id.kg_gridview);
        mAdapter = new RechargeMoneyGridAdapter(mContext, sMoneys,
                RechargeMoneyGridAdapter.UNIT_YUN);
        mGridView.setAdapter(mAdapter);
        if (mFixedNum > 0) {
            updateFixedMoneyNumTextView();
            return;
        }
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            mGridView.setNumColumns(6);
        }
        // 恢复上次支付金额
        mAdapter.setmMoneyIndex(0);
        mRechargeValue = sMoneys[0];

        mGridView.setOnItemClickListener(this);

        mTvOtherNumTip.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mOtherNumLayout.setVisibility(View.VISIBLE);
                mEtOtherNum.requestFocus();
                if (mAdapter.getmMoneyIndex() != -1) {
                    mAdapter.setmMoneyIndex(-1);
                    mAdapter.notifyDataSetChanged();
                    mRechargeValue = getRechargeValueByEditText(mEtOtherNum.getText().toString());
                    updateView();
                }
            }
        });

        mEtOtherNum.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mOtherNumLayout != null && mOtherNumLayout.getVisibility() == View.VISIBLE) {
                    String value = s.toString().trim();
                    if (AppUtil.checkRechargeValueInput(value) || value.length() == 0) {

                        mRechargeValue = getRechargeValueByEditText(value);
                        updateView();
                    } else {
                        mRechargeValue = 0;
                        if (!TextUtils.isEmpty(value)) {
                            mEtOtherNum.setText("");
                        }
                    }
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
        });
        mEtOtherNum.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showSoftInput();
                } else {
                    hideSoftInput(getActivity());
                }
            }
        });
    }

    protected void updateFixedMoneyNumTextView() {
        if (mFixedNum <= 0)
            return;

        mCommonTipsBarMoneyNum.setVisibility(View.VISIBLE);

        int value = mFixedNum;
        if (mSelectedCoupon != null) {
            value = value - mSelectedCoupon.getMoney();
            if (value < 0)
                value = 0;
        }

        mCommonTipsBarMoneyNum.setText(Html.fromHtml("<font color=#666666>支付：</font>"
                + "<font color=#fd9526>" + value + "元" + "</font>"));
        mRechargeLayout.setVisibility(View.GONE);
        mRechargeValue = mFixedNum;

        mCommonTipsBarMoneyNum
                .setPadding(0, 0, 0, (int) (PADDING_BTN * getResources()
                        .getDisplayMetrics().density));
    }

    /**
     * 从EditText中获取充值的数值
     * 
     * @param value
     * @return
     */
    private int getRechargeValueByEditText(String value) {
        if (!TextUtils.isEmpty(value)) {
            return Integer.valueOf(value);
        } else {
            return 0;
        }
    }

    private boolean checkIsSummit() {
        if (mRechargeValue <= 0) {
            showToast("请输入有效的金额");
            return false;
        }
        return true;
    }

    protected void updateView() {

        updateCouponView(mRechargeValue);

        if (mIsRechargeYoubi) {
            updateCanGotKubiTextView(mRechargeValue, ChargeType.TYPE_ALIPAY);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mAdapter.getItem(position) == 0) {
            return;
        }

        if (!NetWorkUtil.isNetworkAvailable(mContext)) {
            showToast("请检查您的网络连接");
            return;
        }

        mEtOtherNum.clearFocus();
        mOtherNumLayout.setVisibility(View.GONE);
        mAdapter.onItemClick(parent, view, position, id);
        mAdapter.notifyDataSetChanged();
        mRechargeValue = (Integer) mAdapter.getItem(position);

        updateView();
    }

    @Override
    public void handleUiMessage(Message msg) {
        super.handleUiMessage(msg);

        if (isDetached() || getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        switch (msg.what) {
            case MSG_ALIPAY_SUCCESS:
                showLayoutRechargeSuccess();

                // 发送支付成功事件
                sendRechargeSuccessEvent(mOrderid, ChargeType.TYPE_ALIPAY, mRechargeValue);

                break;
            case MSG_ALIPAY_FAILED:
                hideLoadingView();
                Bundle bundle = msg.getData();
                if (bundle != null) {
                    String errorMsg = bundle.getString("errorMsg");
                    if (!TextUtils.isEmpty(errorMsg)) {
                        showNoticeDialog(errorMsg);
                    }
                    // 如果是取消支付操作，发送统计
                    String statusCode = bundle.getString("statusCode");
                    int recordtype = 0;// 上报类型 0：支付取消 1：支付错误
                    if ("6001".equals(statusCode)) {
                        recordtype = 0;
                    } else {
                        recordtype = 1;
                    }
                    sendCancelRechargeStatics(recordtype, errorMsg);

                }

                canelRecharge();

                break;

            case MSG_REQUEST_ALIPAY_INFO_FAILED:
                canelRecharge();
                String errorMsg = (String) msg.obj;
                if (!TextUtils.isEmpty(errorMsg)) {
                    showNoticeDialog(errorMsg);
                }
                hideLoadingView();
                break;
            case MSG_REQUEST_ALIPAY_INFO_SUCCESS:
                Message message = Message.obtain();
                message.what = MSG_REQUEST_ALIPAY_INFO;
                message.obj = msg.obj;
                sendBackgroundMessage(message);
                break;
        }
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);
        switch (msg.what) {
            case MSG_BACK_REQUEST_PAY:
                showLoadingView();
                payByali();
                break;

            case MSG_REQUEST_ALIPAY_INFO:
                PayManager.payByAli(getActivity(), (String) msg.obj, onAliPayListener);
                break;

        }
    }

    /**
     * 发送取消支付的统计
     */
    private void sendCancelRechargeStatics(int recordtype, String errormsg) {
        sendCancelRechargeStatics(ChargeType.TYPE_ALIPAY, mRechargeValue, mOrderid, recordtype,
                errormsg);
    }

    /**
     * 显示一些消息提示的确定弹框
     * 
     * @param tips 弹框Message
     */
    private void showNoticeDialog(String tips) {
        final BaseConfirmDialog failedDialog = new BaseConfirmDialog(getActivity());
        failedDialog
                .setOkBtnBackground(Rx.drawable.kg_selector_bottom_single_filleted_corner_retangle);
        failedDialog.setMessage(TextUtils.isEmpty(tips) ? "" : tips);
        failedDialog.setCancelBtnVisibility(View.GONE);
        failedDialog.setContentGravity(Gravity.CENTER);
        failedDialog.setOKBtnText("知道了");
        failedDialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                failedDialog.dismiss();

            }
        });
        failedDialog.show();
    }

    private void showLayoutRechargeSuccess() {
        if (getOnEventListener() != null) {
            getOnEventListener().onRechargeSuccess(ChargeIndexMode.MODE_ALIPAY, mRechargeValue);
        }
    }

    /**
     * 支付宝支付请求
     */
    private void payByali() {
        BasePayRequestParams requestParams = new BasePayRequestParams();
        mOrderid = SDKControler.createNewOrderId();
        if (mIsRechargeYoubi) {
            // 生成唯一字符串
            mOrderid = UUID.randomUUID().toString();
            requestParams.setDirectCharge(0);
        } else {
            requestParams.setDirectCharge(1);
        }

        User user = UserManager.getInstance().getCurrentUserInternal();
        requestParams.setUserName(user.getAccountName());
        requestParams.setChargeType(ChargeType.TYPE_ALIPAY);

        if (mSelectedCoupon != null) {
            requestParams.setCouponId(mSelectedCoupon.getId());
        }

        requestParams.setMoney(1 * 100);
        requestParams.setOutOrderId(mOrderid);
        requestParams.setRole(SDKControler.getRoleName());
        requestParams.setExtension1(SDKControler.getExtension1());
        requestParams.setExtension2(SDKControler.getExtension2());

        AliPayTask httpTask = new AliPayTask();
        AliPayHttpResponse response = httpTask.request(requestParams);
        Message msg = Message.obtain();
        if (response != null && response.isOk()) {
            if (response.isUseful()) {
                if ("0".equals(response.getResult_code())
                        && !TextUtils.isEmpty(response.getResult_msg())) {
                    String info = response.getResult_msg();
                    msg.what = MSG_REQUEST_ALIPAY_INFO_SUCCESS;
                    msg.obj = info;
                } else if ("2".equals(response.getResult_code())) {
                    // code 等于2，全额抵扣，直接跳转到充值成功界面
                    msg.what = MSG_ALIPAY_SUCCESS;
                } else {
                    msg.what = MSG_REQUEST_ALIPAY_INFO_FAILED;
                    msg.obj = response.getResult_msg();
                }
            } else {
                msg.what = MSG_REQUEST_ALIPAY_INFO_FAILED;
                msg.obj = response.getPrompt();
            }
        } else {
            msg.what = MSG_REQUEST_ALIPAY_INFO_FAILED;
            msg.obj = "网络异常，请检查网络连接！";
        }
        sendUiMessage(msg);
    }

    OnAliPayListener onAliPayListener = new OnAliPayListener() {

        @Override
        public void onSuccess() {
            Message msg = new Message();
            msg.what = MSG_ALIPAY_SUCCESS;
            sendUiMessage(msg);
        }

        @Override
        public void onFailed(String errorMsg, String statusCode) {
            Message msg = new Message();
            msg.what = MSG_ALIPAY_FAILED;
            Bundle bundle = new Bundle();
            bundle.putString("errorMsg", errorMsg);
            bundle.putString("statusCode", statusCode);
            msg.setData(bundle);
            sendUiMessage(msg);
        }
    };
}
